package com.example.demo.shiro;

import com.example.demo.bean.Permission;
import com.example.demo.bean.Role;
import com.example.demo.bean.User;
import com.example.demo.jwt.JwtUtils;
import com.example.demo.service.PermissionService;
import com.example.demo.service.RoleService;
import com.example.demo.service.UserService;
import com.example.demo.util.LocalCache;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class ConsumerRealm extends AuthorizingRealm {

    private  final  String REALM_NAME="consumerRealm";
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;
    @Override
    public String getName() {
        return REALM_NAME;
    }

    /**
     * 每一个Ream都有一个supports方法，用于检测是否支持此Token, 默认的采用了return false;
     * false 是不支持
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof  ConsumeToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
        User user=(User) principalCollection.getPrimaryPrincipal();
        if(user ==null){
            return  null;
        }
        List<Role> roles =  roleService.findById(user.getId());
       for (Role role:roles){
           simpleAuthorizationInfo.addRole(role.getRoleName());
           List<Permission> permissions = permissionService.findByRoleId(role.getId());
           for(Permission permission:permissions){
               simpleAuthorizationInfo.addStringPermission(permission.getpName());
           }
       }
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        String token= (String) authenticationToken.getPrincipal();
        //通过token从数据库中或者缓存中拿用户信息
        User user= (User) LocalCache.getMap(token);
//        User user = userService.findUserByName(name);
        if(user==null){
            return  null;
        }
        //第一个参数存的是什么，在doGetAuthorizationInfo方法中getPrimaryPrincipal取到的就是什么
        SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo(user,token,getName());
        return  simpleAuthenticationInfo;
    }


}
